﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Migrations;
using _1._6._2015_EntitiyFramework.Data.Models;

namespace _1._6._2015_EntityFramework.Data
{
    public static class Seeder
    {
        public static void Seed(OrdersDbContext db)
        {
            // think about order and dependancy before you create

            // Seed users and items first
            db.Users.AddOrUpdate(u => new { u.FirstName, u.LastName },
                new User
                {
                    FirstName = "Nick",
                    LastName = "Brittain"
                },
                new User 
                {
                    FirstName = "Susan",
                    LastName = "Anderson"
                }
                );

            db.Items.AddOrUpdate(u => u.Description,
                new Item 
                {
                    Description = "Peanut Butter",
                    Price = 3.99m // m designates decimal will default to double without it you would have error
                },
                new Item 
                {
                    Description = "Refrigerator",
                    Price = 1299.99m // m designates decimal will default to double
                }
                );
            db.SaveChanges(); // commit items to make sure it gets in database

            if (!db.Orders.Any())
            {
                User nick = db.Users.FirstOrDefault(u => u.FirstName == "Nick" && u.LastName == "Brittain"); // will get from db
                User susan = db.Users.FirstOrDefault(u => u.FirstName == "Susan" && u.LastName == "Anderson");
                Order o = new Order
                {
                    OrderDate = DateTime.Now,
                    Total = 45.00m,
                    User = nick // this translates to what sql wants
                };

                db.Orders.Add(o);

                OrderItem oi1 = new OrderItem
                {
                    Order = o, // could not use o.id bacuse it is not in db it would be 0, if SaveChanges first it would fill it out
                    Price = 65.94m,
                    Item = db.Items.FirstOrDefault()
                };

                db.OrderItems.Add(oi1);
             OrderItem oi2 = new OrderItem
                {
                    Order = o,
                    Price = 65.94m,
                    Item = db.Items.FirstOrDefault(i => i.Description == "Refrigerator")
                };

             db.OrderItems.Add(oi2);

             db.SaveChanges(); // If anything throws an error, the entire thing backs out and nothing will happen
                                // not needed bacause it will run automatically (in config seed?)
            }

        }
    }
}
